package encaps.security;

import encaps.entities.Grant;
import encaps.entities.Role;
import encaps.resources.Labels;
import encaps.utils.AbstractCache;
import encaps.utils.DataAccessException;
import encaps.utils.DatabaseUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class RoleCache extends AbstractCache<String, Role> {

    public RoleCache() {
        super();
    }

    @Override
    protected void loadObjectToCache(String requestedRole) throws DataAccessException {
        Role role = null;
        Connection conn = null;
        PreparedStatement ps = null;
        DataSource dataSource = null;
        try {
            dataSource = DatabaseUtil.getDataSource();
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("SELECT name FROM role WHERE name=?");
            ps.setString(1, requestedRole);
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                throw new DataAccessException("Role + " + requestedRole + " not found");
            }
            DatabaseUtil.closeConnection(null, ps);

            ps = conn.prepareStatement("SELECT grant_name FROM role_grant WHERE role_name=?");
            ps.setString(1, requestedRole);
            rs = ps.executeQuery();
            role = new Role(requestedRole);
            while (rs.next()) {
                role.addGrant(new Grant(rs.getString("grant_name")));
            }

            putIntoCache(role.getRoleName(), role);
        } catch (SQLException ex) {
            throw new DataAccessException(Labels.getLabel(Labels.DATABASE_ACCESS_ERROR_MESSAGE), ex);
        } catch (NamingException ex) {
            throw new DataAccessException(Labels.getLabel(Labels.NO_DATASOURCE_FOUND_MESSAGE), ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }
}
